#!/usr/bin/env python
# -*-coding:utf-8-*-
# File    : proxy.py
# Date    : 2021-04-10
# Author  : Tom.Lee

import re,os
# import requests
import httpx
import json
from urllib.parse import urlencode
# requests.packages.urllib3.disable_warnings()

# proxies = {
#   "http": "http://127.0.0.1:8888",
#   "https": "http://127.0.0.1:8888"
# }

proxies = None

class ReqbinSession:
    def __init__(self):
        self.default_cli_headers = {
            'Connection': 'keep-alive',
            'DNT': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
            'Accept': '*/*',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8'
        }
        self.headers = {
            'Host': 'api.reqbin.com', 'Connection': 'keep-alive',
            'Accept': '*/*', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache, no-store, must-revalidate',
            'DNT': '1', 'Content-Type': 'application/json',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
            'Expires': '0', 'Origin': 'https://reqbin.com', 'Sec-Fetch-Site': 'same-site',
            'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Dest': 'empty',
            'Referer': 'https://reqbin.com/', 'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9'
        }
        self.api_node = 'US'
        self.cli_cookies = {}
        self.base_url = "https://api.reqbin.com/api/v1/requests"
        # self.sess = requests.session()
        self.sess = httpx.Client(verify=False, proxies=proxies)
        self.sess.headers = self.headers

    def update_headers(self, headers):
        res = re.findall(r'set-cookie: (\S+)=(\S+?);', headers, re.I)
        # print(dict(res))
        self.cli_cookies = dict(res)

    def request(self, method, url, headers=None, cookies=None,
                query='', post_form='', json_data=None):
        if not headers:
            headers = self.default_cli_headers
        if not isinstance(cookies, dict):
            cookies = self.cli_cookies
        # 编码cookie和请求头
        headers['Cookie'] = ''.join(
            map(lambda x: '{}={}; '.format(*x), cookies.items())).strip()
        headers_str = ''.join(
            map(lambda x: '{}: {}'.format(*x), headers.items()))

        # 编码get表单
        content_type = ''
        content = ''
        if query:
            url += '?' + urlencode(query)
            content_type = 'URLENCODED'

        # 编码post表单
        if post_form:
            content = urlencode(post_form)
            content_type = 'URLENCODED'

        # 编码json数据
        if json_data:
            content_type = 'JSON'
            content = json.dumps(json_data)

        req = {
            "method": method.upper(),
            "url": url,
            "apiNode": self.api_node.upper(),
            "contentType": content_type,
            "content": content,
            "headers": headers_str,
            "errors": "",
            "curlCmd": "",
            "auth": {
                "auth": "noAuth",
                "bearerToken": "",
                "basicUsername": "",
                "basicPassword": "",
                "customHeader": "",
                "encrypted": ""
            },
            "compare": False,
            "idnUrl": url
        }

        json_data = {'id': '0', 'name': '', 'errors': '',
                     'json': json.dumps(req),
                     'deviceId': '6c09a3c6-8a62-4f21-8aa4-dc56017180a5R',
                     'sessionId': 1617445428700}
        # print(self.base_url)
        # resp = self.sess.post(self.base_url, verify=False, json=json_data, proxies=proxies)
        resp = self.sess.post(self.base_url, json=json_data)
        html = resp.json().get("Content")
        headers_str = resp.json().get("Headers")
        # print(headers_str)
        if headers_str:
            self.update_headers(headers_str)
        return html

    def get(self, url, query=None, headers=None, cookies=None):
        html = self.request(
            'GET',
            url,
            headers=headers,
            cookies=cookies,
            query=query)
        return html

    def post(self, url, headers=None, cookies=None,
             query='', post_form='', json_data=None):
        html = self.request(
            'POST',
            url,
            headers=headers,
            cookies=cookies,
            query=query,
            post_form=post_form,
            json_data=json_data)
        return html


if __name__ == '__main__':
    t_url = "https://www.baidu.com/"
    pz = ReqbinSession()
    html = pz.get(t_url)
    print(html)
    print(pz.cli_cookies)
